<?php

namespace app\forms\user;

use Yii;
use app\models\User;
use app\forms\Model;
use yii\db\Exception;
use yii\web\HttpException;

/**
 * 用户登录
 */
class LoginForm extends Model
{
    public $username;
    public $password;

    private $_user = false;

    public function rules()
    {
        return [
            ['username', 'trim'],
            ['username', 'string'],
            ['username', 'required', 'message' => '用户名必填'],

            ['password', 'trim'],
            ['password', 'string'],
            ['password', 'required', 'message' => '密码必填'],
            ['password', 'validatePassword'],

        ];
    }


    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, '错误的用户名或密码');
            }
        }
    }

    /**
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function login($param)
    {
        $form = new self();
        $form->setAttributes($param);
        !$form->validate() ? $form->validateError() : '';

        try {
            $form->_user->generateAccessToken();
            $form->_user->save();
            return ['accessToken' => $form->_user->access_token];
        } catch (Exception $e) {
            $form->serverError();
        }
    }

    public function getUser()
    {
        if ($this->_user === false)
            $this->_user = User::findByUsername($this->username);
        return $this->_user;
    }
}
